/**
 * 交易报表页面JS
 */
$(document).ready(function() {
    // 初始化日期选择器
    $('.datepicker').datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
        language: 'zh-CN'
    });
    
    // 初始化DataTable
    $('#historyReportsTable').DataTable({
        "language": {
            "url": "//cdn.datatables.net/plug-ins/1.10.21/i18n/Chinese.json"
        },
        "pageLength": 5,
        "ordering": false,
        "ajax": {
            "url": "/api/transaction/reports",
            "type": "GET",
            "dataSrc": function(res) {
                if (res.code === 200) {
                    return res.data || [];
                } else {
                    toastr.error('加载报表历史失败：' + res.message);
                    return [];
                }
            }
        },
        "columns": [
            {"data": "reportName"},
            {"data": "reportType"},
            {"data": "timeRange"},
            {"data": "createTime"},
            {"data": null, "orderable": false}
        ],
        "columnDefs": [
            {
                "targets": 1,
                "render": function(data) {
                    var typeMap = {
                        'daily': '日报表',
                        'weekly': '周报表',
                        'monthly': '月报表',
                        'quarterly': '季度报表',
                        'yearly': '年度报表',
                        'custom': '自定义报表'
                    };
                    return typeMap[data] || data;
                }
            },
            {
                "targets": -1,
                "render": function(data) {
                    var viewBtn = '<button class="btn btn-sm btn-info mr-1 view-report-btn" data-id="' + data.id + '"><i class="fas fa-eye"></i></button>';
                    var downloadBtn = '<button class="btn btn-sm btn-primary mr-1 download-report-btn" data-id="' + data.id + '"><i class="fas fa-download"></i></button>';
                    var deleteBtn = '<button class="btn btn-sm btn-danger delete-report-btn" data-id="' + data.id + '"><i class="fas fa-trash"></i></button>';
                    return viewBtn + downloadBtn + deleteBtn;
                }
            }
        ]
    });
    
    // 模板选择
    $('.template-card').click(function() {
        $('.template-card').removeClass('selected');
        $(this).addClass('selected');
        var template = $(this).data('template');
        $('#reportTemplate').val(template);
    });
    
    // 生成报表按钮点击事件
    $('#generateReportBtn').click(function() {
        // 显示加载中
        $('#reportPreview').html('<div class="text-center py-5"><i class="fas fa-spinner fa-spin fa-3x text-primary mb-3"></i><h4>正在生成报表，请稍候...</h4></div>');
        
        // 收集表单数据
        var formData = {
            reportType: $('#reportType').val(),
            reportTemplate: $('#reportTemplate').val(),
            startDate: $('#startDate').val(),
            endDate: $('#endDate').val(),
            warehouseId: $('#warehouseSelect').val(),
            transactionType: $('#transactionType').val(),
            includeCharts: $('#includeCharts').is(':checked'),
            includeTables: $('#includeTables').is(':checked'),
            includeSummary: $('#includeSummary').is(':checked')
        };
        
        // 发送请求生成报表
        $.ajax({
            url: '/api/transaction/report/generate',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(res) {
                if (res.code === 200) {
                    // 显示报表预览
                    showReportPreview(res.data);
                    
                    // 刷新历史报表列表
                    $('#historyReportsTable').DataTable().ajax.reload();
                } else {
                    toastr.error('生成报表失败：' + res.message);
                    // 显示空报表预览
                    showEmptyReportPreview();
                }
            },
            error: function(xhr) {
                toastr.error('生成报表失败：' + xhr.statusText);
                // 显示空报表预览
                showEmptyReportPreview();
                
                // 使用模拟数据展示
                setTimeout(function() {
                    generateSampleReport();
                }, 1500);
            }
        });
    });
    
    // 导出按钮事件
    $('#exportPdf').click(function(e) {
        e.preventDefault();
        exportReport('pdf');
    });
    
    $('#exportExcel').click(function(e) {
        e.preventDefault();
        exportReport('excel');
    });
    
    $('#exportWord').click(function(e) {
        e.preventDefault();
        exportReport('word');
    });
    
    $('#exportCsv').click(function(e) {
        e.preventDefault();
        exportReport('csv');
    });
    
    // 打印按钮事件
    $('#printReportBtn').click(function() {
        printReport();
    });
    
    // 查看报表按钮点击事件
    $('#historyReportsTable').on('click', '.view-report-btn', function() {
        var reportId = $(this).data('id');
        viewReport(reportId);
    });
    
    // 下载报表按钮点击事件
    $('#historyReportsTable').on('click', '.download-report-btn', function() {
        var reportId = $(this).data('id');
        downloadReport(reportId);
    });
    
    // 删除报表按钮点击事件
    $('#historyReportsTable').on('click', '.delete-report-btn', function() {
        var reportId = $(this).data('id');
        deleteReport(reportId);
    });
});

// 显示空报表预览
function showEmptyReportPreview() {
    $('#reportPreview').html(`
        <div class="text-center py-5">
            <i class="fas fa-chart-bar fa-4x text-muted mb-3"></i>
            <h4 class="text-muted">请配置并生成报表</h4>
            <p class="text-muted">在左侧设置报表参数后点击"生成报表"按钮</p>
        </div>
    `);
}

// 显示报表预览
function showReportPreview(reportData) {
    // 根据返回的HTML内容展示报表
    $('#reportPreview').html(reportData.reportHtml);
    
    // 初始化报表中的图表
    if (reportData.hasCharts) {
        setTimeout(function() {
            initReportCharts(reportData.chartData);
        }, 100);
    }
}

// 导出报表
function exportReport(format) {
    // 收集表单数据
    var formData = {
        reportType: $('#reportType').val(),
        reportTemplate: $('#reportTemplate').val(),
        startDate: $('#startDate').val(),
        endDate: $('#endDate').val(),
        warehouseId: $('#warehouseSelect').val(),
        transactionType: $('#transactionType').val(),
        includeCharts: $('#includeCharts').is(':checked'),
        includeTables: $('#includeTables').is(':checked'),
        includeSummary: $('#includeSummary').is(':checked'),
        format: format
    };
    
    // 构建查询参数
    var queryParams = $.param(formData);
    
    // 打开下载窗口
    window.open('/api/transaction/report/export?' + queryParams, '_blank');
}

// 打印报表
function printReport() {
    var printContents = document.getElementById('reportPreview').innerHTML;
    var originalContents = document.body.innerHTML;
    
    document.body.innerHTML = `
        <div class="container">
            <div class="row">
                <div class="col-12">
                    ${printContents}
                </div>
            </div>
        </div>
    `;
    
    window.print();
    
    document.body.innerHTML = originalContents;
    
    // 重新初始化页面
    location.reload();
}

// 查看历史报表
function viewReport(reportId) {
    $.ajax({
        url: '/api/transaction/report/' + reportId,
        type: 'GET',
        success: function(res) {
            if (res.code === 200) {
                // 显示报表预览
                showReportPreview(res.data);
            } else {
                toastr.error('查看报表失败：' + res.message);
            }
        },
        error: function(xhr) {
            toastr.error('查看报表失败：' + xhr.statusText);
        }
    });
}

// 下载历史报表
function downloadReport(reportId) {
    // 打开下载窗口
    window.open('/api/transaction/report/' + reportId + '/download', '_blank');
}

// 删除历史报表
function deleteReport(reportId) {
    if (confirm('确定要删除此报表吗？')) {
        $.ajax({
            url: '/api/transaction/report/' + reportId,
            type: 'DELETE',
            success: function(res) {
                if (res.code === 200) {
                    toastr.success('删除报表成功');
                    // 刷新历史报表列表
                    $('#historyReportsTable').DataTable().ajax.reload();
                } else {
                    toastr.error('删除报表失败：' + res.message);
                }
            },
            error: function(xhr) {
                toastr.error('删除报表失败：' + xhr.statusText);
            }
        });
    }
}

// 初始化报表图表
function initReportCharts(chartData) {
    // 交易类型分布图
    if (document.getElementById('reportTypeChart')) {
        var typeChart = echarts.init(document.getElementById('reportTypeChart'));
        typeChart.setOption(chartData.typeChartOption);
    }
    
    // 交易金额趋势图
    if (document.getElementById('reportTrendChart')) {
        var trendChart = echarts.init(document.getElementById('reportTrendChart'));
        trendChart.setOption(chartData.trendChartOption);
    }
    
    // 窗口大小变化时重新调整图表大小
    window.addEventListener('resize', function() {
        if (document.getElementById('reportTypeChart')) {
            echarts.getInstanceByDom(document.getElementById('reportTypeChart')).resize();
        }
        if (document.getElementById('reportTrendChart')) {
            echarts.getInstanceByDom(document.getElementById('reportTrendChart')).resize();
        }
    });
}

// 获取报表类型名称
function getReportTypeName(type) {
    var types = {
        'daily': '日',
        'weekly': '周',
        'monthly': '月',
        'quarterly': '季度',
        'yearly': '年度',
        'custom': '自定义'
    };
    return types[type] || '';
}

// 生成示例报表
function generateSampleReport() {
    var reportType = $('#reportType').val();
    var reportTemplate = $('#reportTemplate').val();
    var startDate = $('#startDate').val() || '2023-03-01';
    var endDate = $('#endDate').val() || '2023-03-31';
    var warehouse = $('#warehouseSelect').val();
    var transactionType = $('#transactionType').val();
    
    var reportHtml = `
        <div class="report-header text-center mb-4">
            <h3>交易${getReportTypeName(reportType)}报表</h3>
            <p class="text-muted">报表周期: ${startDate} 至 ${endDate}</p>
        </div>
        
        <div class="report-summary mb-4">
            <h4>报表摘要</h4>
            <div class="row">
                <div class="col-md-3">
                    <div class="card bg-light">
                        <div class="card-body text-center">
                            <h5>交易总数</h5>
                            <h2>1,284</h2>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-light">
                        <div class="card-body text-center">
                            <h5>交易总额</h5>
                            <h2>¥1,256,890</h2>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-light">
                        <div class="card-body text-center">
                            <h5>日均交易量</h5>
                            <h2>42.8</h2>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-light">
                        <div class="card-body text-center">
                            <h5>环比增长</h5>
                            <h2>+12.5%</h2>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row mb-4">
            <div class="col-md-6">
                <h4>交易类型分布</h4>
                <div id="reportTypeChart" style="height: 300px;"></div>
            </div>
            <div class="col-md-6">
                <h4>交易金额趋势</h4>
                <div id="reportTrendChart" style="height: 300px;"></div>
            </div>
        </div>
        
        <div class="report-details mb-4">
            <h4>交易明细</h4>
            <table class="table table-striped table-bordered">
                <thead>
                    <tr>
                        <th>交易ID</th>
                        <th>交易类型</th>
                        <th>产品名称</th>
                        <th>数量</th>
                        <th>单位</th>
                        <th>金额</th>
                        <th>仓库</th>
                        <th>交易时间</th>
                        <th>状态</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>TX20230301001</td>
                        <td>采购入库</td>
                        <td>大米</td>
                        <td>1000</td>
                        <td>kg</td>
                        <td>¥5,000</td>
                        <td>1号仓库</td>
                        <td>2023-03-01 09:30:22</td>
                        <td><span class="badge badge-success">已完成</span></td>
                    </tr>
                    <tr>
                        <td>TX20230302001</td>
                        <td>销售出库</td>
                        <td>小麦</td>
                        <td>500</td>
                        <td>kg</td>
                        <td>¥3,000</td>
                        <td>2号仓库</td>
                        <td>2023-03-02 14:15:47</td>
                        <td><span class="badge badge-success">已完成</span></td>
                    </tr>
                    <tr>
                        <td>TX20230305001</td>
                        <td>库存调拨</td>
                        <td>玉米</td>
                        <td>800</td>
                        <td>kg</td>
                        <td>¥4,000</td>
                        <td>1号仓库→3号仓库</td>
                        <td>2023-03-05 11:05:36</td>
                        <td><span class="badge badge-success">已完成</span></td>
                    </tr>
                    <tr>
                        <td>TX20230310001</td>
                        <td>库存盘点</td>
                        <td>大豆</td>
                        <td>1200</td>
                        <td>kg</td>
                        <td>¥6,000</td>
                        <td>2号仓库</td>
                        <td>2023-03-10 16:22:10</td>
                        <td><span class="badge badge-success">已完成</span></td>
                    </tr>
                    <tr>
                        <td>TX20230315001</td>
                        <td>采购入库</td>
                        <td>花生</td>
                        <td>600</td>
                        <td>kg</td>
                        <td>¥4,800</td>
                        <td>3号仓库</td>
                        <td>2023-03-15 10:45:33</td>
                        <td><span class="badge badge-success">已完成</span></td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <div class="report-footer text-right">
            <p class="text-muted">报表生成时间: ${new Date().toLocaleString()}</p>
            <p class="text-muted">报表生成人: 系统管理员</p>
        </div>
    `;
    
    $('#reportPreview').html(reportHtml);
    
    // 初始化图表
    setTimeout(function() {
        initSampleReportCharts();
    }, 100);
}

// 初始化示例报表图表
function initSampleReportCharts() {
    // 交易类型分布图
    var typeChart = echarts.init(document.getElementById('reportTypeChart'));
    var typeOption = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: ['采购入库', '销售出库', '库存调拨', '库存盘点']
        },
        series: [
            {
                name: '交易类型',
                type: 'pie',
                radius: ['50%', '70%'],
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '18',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: [
                    {value: 335, name: '采购入库'},
                    {value: 310, name: '销售出库'},
                    {value: 234, name: '库存调拨'},
                    {value: 135, name: '库存盘点'}
                ]
            }
        ]
    };
    typeChart.setOption(typeOption);
    
    // 交易金额趋势图
    var trendChart = echarts.init(document.getElementById('reportTrendChart'));
    var trendOption = {
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            data: ['3/1', '3/5', '3/10', '3/15', '3/20', '3/25', '3/30']
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: '¥{value}'
            }
        },
        series: [{
            data: [15000, 22000, 18000, 25000, 30000, 28000, 32000],
            type: 'line',
            smooth: true,
            areaStyle: {}
        }]
    };
    trendChart.setOption(trendOption);
    
    // 窗口大小变化时重新调整图表大小
    window.addEventListener('resize', function() {
        typeChart.resize();
        trendChart.resize();
    });
} 